package com.prig.base.controller;

import com.prig.base.DTO.input.AdminRoleDto;
import com.prig.base.DTO.input.AdminRolesDto;
import com.prig.base.DTO.output.AdminRolesOutDto;
import com.prig.base.entity.AdminRoleRelationId;
import com.prig.base.entity.Role;
import com.prig.base.service.AdminRoleService;
import com.prig.base.service.RoleService;
import com.prig.base.util.response.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(path = "/adminRole")
@Api(value = "管理员角色关联")
public class AdminRoleController {
    @Autowired
    public void setAdminService(RoleService roleService) {
        this.roleService = roleService;
    }

    private RoleService roleService;

    private AdminRoleService adminRoleService;
    @Autowired
    public void setAdminRoleService(AdminRoleService adminRoleService) {
        this.adminRoleService = adminRoleService;
    }

    @RequestMapping(path = "/add",method = RequestMethod.POST)
    @ApiOperation(value = "添加管理员角色关联",notes = "添加管理员角色关联")
    @RequiresPermissions("adminRole:add")
    public Result add(@RequestBody @Valid AdminRoleDto dto){
        adminRoleService.add(new AdminRoleRelationId(dto.getAdminId(),dto.getRoleId()));
        return new Result();
    }
    @RequestMapping(path = "/delete",method = RequestMethod.POST)
    @ApiOperation(value = "删除管理员角色关联",notes = "删除管理员角色关联")
    @RequiresPermissions("adminRole:delete")
    public Result delete(@RequestBody @Valid AdminRoleDto dto){
        adminRoleService.delete(new AdminRoleRelationId(dto.getAdminId(),dto.getRoleId()));
        return new Result();
    }
    @GetMapping(path = "/{adminId}")
    @RequiresPermissions("adminRole:get")
    public Result getAdminRoles(
            @PathVariable(name="adminId") long adminId
    ){
        List<Role> all = roleService.getRoles();
        List<Role> exist =roleService.getRoles(adminId);
        return new Result<>(new AdminRolesOutDto(all,exist,adminId));
    }
    @PostMapping(path = "/{adminId}")
    @RequiresPermissions("adminRole:update")
    public Result updateAdminRoles(
            @PathVariable(name="adminId") long adminId,
            @RequestBody AdminRolesDto dto
    ){
        String[] idsStr = dto.getStrIds().split(",");
        List<AdminRoleRelationId> list = Arrays.stream(idsStr)
                .map(str->new AdminRoleRelationId(adminId,Long.parseLong(str)))
                .collect(Collectors.toList());
        adminRoleService.delete(adminId);
        adminRoleService.add(list);
        return new Result();
    }
}
